package com.yimaxiaoerlang.im_core.manager;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.test.platform.app.InstrumentationRegistry;

import com.yimaxiaoerlang.http.GsonUtils;
import com.yimaxiaoerlang.http.NetException;
import com.yimaxiaoerlang.http.NetModel;
import com.yimaxiaoerlang.http.ResultListener;
import com.yimaxiaoerlang.http.RetrofitHelper;
import com.yimaxiaoerlang.im_core.core.YMIMClient;
import com.yimaxiaoerlang.im_core.core.other.YMClientService;
import com.yimaxiaoerlang.im_core.core.other.YMConnectCallback;
import com.yimaxiaoerlang.im_core.core.other.YMConnectError;
import com.yimaxiaoerlang.im_core.core.other.YMConnectionStatus;
import com.yimaxiaoerlang.im_core.core.other.YMConnectionStatusListener;
import com.yimaxiaoerlang.im_core.core.other.YMReceiveMessageListener;
import com.yimaxiaoerlang.im_core.core.other.YMResultCallback;
import com.yimaxiaoerlang.im_core.core.callback.MessageCallback;
import com.yimaxiaoerlang.im_core.model.YMChatroomEntity;
import com.yimaxiaoerlang.im_core.model.YMRoomEntity;
import com.yimaxiaoerlang.im_core.model.conversation.YMConversation;
import com.yimaxiaoerlang.im_core.model.message.YMCustomMessage;
import com.yimaxiaoerlang.im_core.model.message.YMFileMessage;
import com.yimaxiaoerlang.im_core.model.message.YMImageMessage;
import com.yimaxiaoerlang.im_core.model.message.YMMessage;
import com.yimaxiaoerlang.im_core.model.message.YMMessageContent;
import com.yimaxiaoerlang.im_core.model.message.YMTextMessage;
import com.yimaxiaoerlang.im_core.model.message.YMVideoMessage;
import com.yimaxiaoerlang.im_core.model.message.YMVoiceMessage;
import com.yimaxiaoerlang.im_core.model.YMApplyUserListEntity;
import com.yimaxiaoerlang.im_core.model.YMContacts;
import com.yimaxiaoerlang.im_core.model.YMGroupEntity;
import com.yimaxiaoerlang.im_core.model.YMServiceConversation;
import com.yimaxiaoerlang.im_core.model.YMServiceConversationResult;
import com.yimaxiaoerlang.im_core.model.YMServiceMessageInfo;
import com.yimaxiaoerlang.im_core.model.YMSocketMessage;
import com.yimaxiaoerlang.im_core.model.YMSocketMessageContent;
import com.yimaxiaoerlang.socket.ClientStateListener;
import com.yimaxiaoerlang.socket.IMWbeSocketClient;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class YMServiceManager implements ClientStateListener {
    private static final String TAG = "IMCoreClient";
    private static final String TOEKN_HEADER = "Sec-WebSocket-Protocol";
    private static final int LOGOUT_TAG = 21;
    private static final int RTC_TAG = 205;

    public static YMServiceManager getInstance() {
        return SingletonHolder.sInstance;
    }

    private String socketAddress = "wss://im.yimaxiaoerlang.cn/websocket";
    private String apiAddress = "https://im.yimaxiaoerlang.cn";

    private IMWbeSocketClient mClient;
    private YMConnectCallback connectCallback;
    private YMConnectionStatusListener statusListener;
    private String userId;//用于判断发送方向
    public static Handler mHandler;

    private List<YMReceiveMessageListener> receiveListeners = new ArrayList<>();

    private MessageCallback rtcCallback;
    private String nowToken = "";
    private static final String PreferenceName = "YM-IM";

    public void setRtcCallback(MessageCallback rtcCallback) {
        this.rtcCallback = rtcCallback;
    }

    @Override
    public void onConnected() {

        runUIThread(new Runnable() {
            @Override
            public void run() {
                if (connectCallback != null) {
                    connectCallback.onSuccess("");
                    connectCallback = null;
                }
                if (statusListener != null) {
                    statusListener.onChanged(YMConnectionStatus.CONNECTED);
                }
            }
        });

    }

    @Override
    public void onDisconnected() {
        runUIThread(new Runnable() {
            @Override
            public void run() {

                if (statusListener != null) {
                    statusListener.onChanged(YMConnectionStatus.UNCONNECTED);
                }
            }
        });
    }

    @Override
    public void onReceiveMessage(String msg) {
        runUIThread(new Runnable() {
            @Override
            public void run() {
                handleMessage(msg);
            }
        });
    }

    @Override
    public void authenticationError() {
        runUIThread(new Runnable() {
            @Override
            public void run() {
                if (connectCallback != null) {
                    connectCallback.onError(YMConnectError.AUTHENTICATIONERROR);
                    connectCallback = null;
                }
            }
        });
    }


    private static class SingletonHolder {
        static YMServiceManager sInstance = new YMServiceManager();

        private SingletonHolder() {

        }
    }

    private YMServiceManager() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * 设置地址
     *
     * @param api
     * @param socket
     */
    public void configAddress(String api, String socket) {
        if (api == null || "".equals(api) || socket == null || "".equals(socket)) return;
        socketAddress = socket;
        apiAddress = api;
        RetrofitHelper.getInstance().init(apiAddress);

    }

    /**
     * 通过token进行链接
     *
     * @param token
     * @param callback
     */
    public static void connect(String token, String userId, final YMConnectCallback callback) {
        if (YMServiceManager.SingletonHolder.sInstance.mClient != null && SingletonHolder.sInstance.nowToken.equals(token) && YMServiceManager.SingletonHolder.sInstance.mClient.isOpen()) {
            return;
        }
        if (YMServiceManager.SingletonHolder.sInstance.mClient != null && YMServiceManager.SingletonHolder.sInstance.mClient.isOpen()) {
            YMServiceManager.SingletonHolder.sInstance.mClient.closeConnect();
        }

        SingletonHolder.sInstance.nowToken = token;
        if (TextUtils.isEmpty(YMServiceManager.SingletonHolder.sInstance.socketAddress) || TextUtils.isEmpty(YMServiceManager.SingletonHolder.sInstance.apiAddress)) {
            Log.e(TAG, "未设置socket地址或api访问地址");
            callback.onError(YMConnectError.UNSEETINGURL);
            return;
        }
        if (token == null || token.isEmpty()) {
            Log.e(TAG, "token is empty");
            callback.onError(YMConnectError.TOKENEMTY);
            return;
        }
        if (userId == null || userId.isEmpty()) {
            Log.e(TAG, "userId is empty");
            callback.onError(YMConnectError.USERIDEMTYP);
            return;
        }
        saveToken(token);
        SingletonHolder.sInstance.userId = userId;
        YMServiceManager.SingletonHolder.sInstance.connectCallback = callback;
        //设置地址
        try {
            YMServiceManager.SingletonHolder.sInstance.mClient = new IMWbeSocketClient(new URI(SingletonHolder.sInstance.socketAddress));
            YMServiceManager.SingletonHolder.sInstance.mClient.setStateListener(SingletonHolder.sInstance);
        } catch (URISyntaxException e) {
            Log.e(TAG, "socketclient客户端设置发生错误");
        }
        //添加token
        YMServiceManager.SingletonHolder.sInstance.mClient.addHeader(TOEKN_HEADER, token);
        YMServiceManager.SingletonHolder.sInstance.mClient.connect();
    }

    private static void saveToken(String token) {
        Context appContext = YMIMClient.getAppContext();
        SharedPreferences sp = appContext.getSharedPreferences(PreferenceName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("token", token);
        editor.apply();
    }

    public static String getToken() {
        Context appContext = YMIMClient.getAppContext();
        SharedPreferences sp = appContext.getSharedPreferences(PreferenceName, Context.MODE_PRIVATE);
        return sp.getString("token", "");
    }

    /**
     * 断开链接
     */
    public static void logout() {
        SingletonHolder.sInstance.mClient.closeConnect();
    }


    /**
     * 设置链接状态监听
     *
     * @param listener
     */
    public static void setConnectionStatusListener(YMConnectionStatusListener listener) {
        YMServiceManager.SingletonHolder.sInstance.statusListener = listener;
    }

    /**
     * 移除链接状态监听
     */
    public static void removeConnectionStatusListener() {
        YMServiceManager.SingletonHolder.sInstance.statusListener = null;
    }

    /**
     * 获取当前的链接状态
     *
     * @return
     */
    public static YMConnectionStatus getCurrentConnectionStatus() {
        if (YMServiceManager.SingletonHolder.sInstance.mClient != null) {
            return SingletonHolder.sInstance.mClient.isOpen() ? YMConnectionStatus.CONNECTED : YMConnectionStatus.UNCONNECTED;
        }
        return YMConnectionStatus.UNKOWN;
    }


    /**
     * 处理消息
     *
     * @param msg
     */
    private void handleMessage(String msg) {
        if (rtcCallback != null) {
            rtcCallback.recive(msg);
        }
        Log.e(TAG, "接收到消息: " + msg);
        Log.e(TAG, "注册的监听: " + receiveListeners.size());
        YMSocketMessage message = getMessage(msg);
        if (message == null) return;
        YMSocketMessageContent content = message.getMessage();
        if (content == null) return;
        if (content.getMsgType() == LOGOUT_TAG) {
            mClient.closeConnect();
            if (statusListener != null) {
                statusListener.onChanged(YMConnectionStatus.LOGIN_OTHER);
            }
            return;
        }
        YMMessage loaclMessage = message.toLocalMessage(userId);
        if (loaclMessage == null) {
            return;
        }
        for (YMReceiveMessageListener receiveListener : receiveListeners) {
            receiveListener.onReceiveMessage(loaclMessage);
        }
    }


    /**
     * ui线程执行
     *
     * @param runnable
     */
    private void runUIThread(Runnable runnable) {
        mHandler.post(runnable);
    }

    /**
     * 把socket的消息转换成消息对象
     *
     * @param msg
     * @return
     */
    private YMSocketMessage getMessage(String msg) {
        return GsonUtils.toBean(msg, YMSocketMessage.class);
    }


    /**
     * 根据类型获取会话列表
     *
     * @param typeArray
     * @param callback
     */
    public static void getConversationList(List<YMConversation.ConversationType> typeArray, int pageIndex, int pageSize, Integer label, final YMResultCallback<List<YMConversation>> callback) {

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < typeArray.size(); i++) {
            buffer.append(typeArray.get(i).getValue());
            if (i != typeArray.size() - 1) {
                buffer.append(",");
            }
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("label", label == null ? "" : label);
        map.put("queryStr", "");
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        map.put("groupType", buffer.toString());


        NetModel.getInstance()
                .request(RetrofitHelper.getRequest(YMClientService.class).conversationList(map), new ResultListener<YMServiceConversationResult<YMServiceConversation>>() {
                    @Override
                    public void onSuccess(YMServiceConversationResult<YMServiceConversation> serviceConversationResult) {
                        SingletonHolder.sInstance.runUIThread(new Runnable() {
                            @Override
                            public void run() {
                                serviceConversationoIMConversation(serviceConversationResult, callback);
                            }
                        });
                    }

                    @Override
                    public void onError(NetException netException) {
                        SingletonHolder.sInstance.runUIThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onFail(netException.getCode());
                            }
                        });
                    }
                });
    }

    /**
     * 将服务端返回数据转换成封装的数据
     *
     * @param result
     * @param callback
     */
    private static void serviceConversationoIMConversation(YMServiceConversationResult<YMServiceConversation> result, YMResultCallback<List<YMConversation>> callback) {
        List<YMServiceConversation> serviceConversations = result.getRecords();
        List<YMConversation> conversationList = new ArrayList<>();
        for (YMServiceConversation serviceConversation : serviceConversations) {
            conversationList.add(serviceConversation.toConversation());
        }
        callback.onCallback(conversationList);
    }


    /**
     * 添加收到消息的监听
     *
     * @param listener
     */
    public static void addReceiveMessageListener(YMReceiveMessageListener listener) {
        if (!SingletonHolder.sInstance.receiveListeners.contains(listener)) {
            SingletonHolder.sInstance.receiveListeners.add(listener);
        }
    }

    /**
     * 移除收到消息的监听
     *
     * @param listener
     */
    public static void removeReceiveMessageListener(YMReceiveMessageListener listener) {
        if (SingletonHolder.sInstance.receiveListeners.contains(listener)) {
            SingletonHolder.sInstance.receiveListeners.remove(listener);
        }
    }

    /**
     * 获取通讯录联系人
     *
     * @param typeArray
     * @param pageIndex
     * @param pageSize
     * @param queryStr
     * @param callback
     */
    public static void getContacts(List<YMConversation.ConversationType> typeArray, int pageIndex, int pageSize, String queryStr, final YMResultCallback<List<YMContacts>> callback) {

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < typeArray.size(); i++) {
            buffer.append(typeArray.get(i).getValue());
            if (i != typeArray.size() - 1) {
                buffer.append(",");
            }
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("queryStr", "");
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        map.put("groupType", buffer.toString());

        NetModel.getInstance()
                .request(RetrofitHelper.getRequest(YMClientService.class).contactsList(map), new ResultListener<ArrayList<YMContacts>>() {
                    @Override
                    public void onSuccess(ArrayList<YMContacts> arrayList) {

                        SingletonHolder.sInstance.runUIThread(new Runnable() {
                            @Override
                            public void run() {
                                if (callback != null) {
                                    callback.onCallback(arrayList);
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(NetException netException) {
                        SingletonHolder.sInstance.runUIThread(new Runnable() {
                            @Override
                            public void run() {
                                if (callback != null) {
                                    callback.onFail(netException.getCode());
                                }

                            }
                        });
                    }
                });


    }


    /**
     * 单聊，需要创建群聊
     *
     * @param groupLable
     * @param targetId
     * @param callback
     */
    public static void createPrivateChat(String groupLable, String targetId, final YMResultCallback<YMConversation> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("label", groupLable);
        map.put("tid", targetId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).createPrivateChar(map), new ResultListener<YMServiceConversation>() {
            @Override
            public void onSuccess(YMServiceConversation serviceConversation) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(serviceConversation.toConversation());
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 会话详情
     *
     * @param groupId
     * @param callback
     */
    public static void conversationDel(String groupId, final YMResultCallback<YMConversation> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).groupDetail(map), new ResultListener<YMServiceConversation>() {
            @Override
            public void onSuccess(YMServiceConversation serviceConversation) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(serviceConversation.toConversation());
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 置顶会话
     *
     * @param groupId
     * @param callback
     */
    public static void setConversationTop(String groupId, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).setConversationTop(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    public static void bindGTPushClientId(String userId, String clientId, final YMResultCallback<Object> callback) {
        HashMap<String, String> map = new HashMap<>();
        map.put("cid", clientId);
        map.put("uid", userId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).bindPushClientId(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 设置消息免打扰
     *
     * @param groupId
     * @param callback
     */
    public static void setConversationDisturb(String groupId, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).setConversationDisturb(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 离开群组
     *
     * @param groupId  群组id
     * @param callback
     */
    public static void leaveGroup(String groupId, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).leaveGroup(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 修改群名称
     *
     * @param groupId
     * @param callback
     */
    public static void changeGroupName(String groupId, String groupName, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("groupName", groupName);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).changeGroupName(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 获取好友详情
     *
     * @param userId   好友id
     * @param callback
     */
    public static void getFriendDetail(String userId, final YMResultCallback<YMContacts> callback) {
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).getFriendDetail(userId), new ResultListener<YMContacts>() {
            @Override
            public void onSuccess(YMContacts data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 搜索用户
     *
     * @param keyword  搜索关键字
     * @param callback
     */
    public static void searchUser(String keyword, final YMResultCallback<List<YMContacts>> callback) {
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).searchUser(keyword), new ResultListener<List<YMContacts>>() {
            @Override
            public void onSuccess(List<YMContacts> data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 更改好友备注
     *
     * @param userId   用户id
     * @param noteName 备注
     * @param callback
     */
    public static void changeFriendNote(String userId, String noteName, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("tid", userId);
        map.put("noteName", noteName);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).changeFriendNote(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 获取消息列表
     */
    public static void messageList(String groupId, int pageIndex, int pageSize, String queryStr, final YMResultCallback<List<YMMessage>> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        map.put("queryStr", queryStr);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).messageList(map), new ResultListener<YMServiceConversationResult<YMServiceMessageInfo>>() {
            @Override
            public void onSuccess(YMServiceConversationResult<YMServiceMessageInfo> serviceConversation) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        serviceMessageToLocal(serviceConversation.getRecords(), callback);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 将服务端返回的消息列表转换成本地消息列表
     *
     * @param list
     * @param callback
     */
    private static void serviceMessageToLocal(List<YMServiceMessageInfo> list, YMResultCallback<List<YMMessage>> callback) {

        List<YMMessage> messageList = new ArrayList<>();
        for (YMServiceMessageInfo serviceMessageInfo : list) {
            messageList.add(serviceMessageInfo.toMessage(getInstance().userId));
        }
        callback.onCallback(messageList);
    }

    /***
     * 阅读消息
     * @param message
     */
    public static void readMessage(YMMessage message) {
//        {"gid":629096697573814272,"message":{"msgType":0,"msgId":630651647789510656}}
        YMSocketMessage socketMessage = new YMSocketMessage();
        socketMessage.setGid(message.getTargetId());
        YMSocketMessageContent socketMessageContent = new YMSocketMessageContent();
        socketMessageContent.setMsgType(0);
        socketMessageContent.setMsgId(message.getMessageId());
        socketMessage.setMessage(socketMessageContent);
        if (SingletonHolder.sInstance.mClient != null && SingletonHolder.sInstance.mClient.isOpen())
            SingletonHolder.sInstance.mClient.send(GsonUtils.toJson(socketMessage));
    }

    /**
     * 发送消息
     *
     * @param message
     */
    public static void sendMessage(YMMessage message, final YMResultCallback<Boolean> callback) {
        YMMessageContent content = message.getContent();
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", message.getTargetId());
        if (content instanceof YMTextMessage) {
            map.put("message", ((YMTextMessage) content).getContent());
            map.put("msgType", 101);
        } else if (content instanceof YMVoiceMessage) {
            HashMap<String, Object> extras = new HashMap<>();
            extras.put("duration", ((YMVoiceMessage) content).getDuration());
            map.put("extraData", extras);
            map.put("msgType", 102);
            map.put("message", ((YMVoiceMessage) content).getUrl());
        } else if (content instanceof YMImageMessage) {
            YMImageMessage imageMessage = ((YMImageMessage) content);
            HashMap<String, Object> extras = new HashMap<>();
            extras.put("height", imageMessage.getHeight());
            extras.put("width", imageMessage.getWidth());
            map.put("extraData", extras);
            map.put("msgType", 104);
            map.put("message", imageMessage.getUrl());
        } else if (content instanceof YMVideoMessage) {
            YMVideoMessage videoMessage = (YMVideoMessage) content;
            HashMap<String, Object> extras = new HashMap<>();
            extras.put("height", videoMessage.getHeight());
            extras.put("width", videoMessage.getWidth());
            extras.put("duration", videoMessage.getDuration());
            extras.put("imageUrl", videoMessage.getThumbnail());
            map.put("extraData", extras);
            map.put("msgType", 103);
            map.put("message", videoMessage.getUrl());
        } else if (content instanceof YMCustomMessage) {
            map.put("message", ((YMCustomMessage) content).getContent());
            map.put("msgType", 100);
        }


        if (map == null) return;

        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).sendMessage(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object obj) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });

    }

    /**
     * 删除会话
     *
     * @param groupId
     * @param callback
     */
    public static void delMessage(String groupId, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).delMessage(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object obj) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 清空会话
     *
     * @param groupId
     * @param callback
     */
    public static void clearMessage(String groupId, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).clearMessage(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object obj) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 添加好友
     *
     * @param tid
     * @param utMsg
     * @param callback
     */
    public static void addFriend(String tid, String utMsg, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("tid", tid);
        map.put("utMsg", utMsg);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).addFriend(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object obj) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 处理好友申请
     *
     * @param ufState
     * @param ufid
     * @param callback
     */
    public static void handleFriend(int ufState, String ufid, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("ufState", ufState);
        map.put("ufid", ufid);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).handleFriend(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object obj) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 获取全部聊天室列表
     *
     * @param callback
     */
    public static void searchRoomList(String keyword, final YMResultCallback<List<YMChatroomEntity>> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("groupName", keyword);
        map.put("groupType", 2);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).searchRoomList(map), new ResultListener<List<YMChatroomEntity>>() {
            @Override
            public void onSuccess(List<YMChatroomEntity> data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 创建群聊
     *
     * @param groupAvatar
     * @param groupName
     * @param uidList
     * @param callback
     */
    public static void createGroup(String groupAvatar, String groupName, String uidList, final YMResultCallback<YMGroupEntity> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("groupAvatar", groupAvatar);
        map.put("groupName", groupName);
        map.put("uidList", uidList);
        map.put("groupType", 1);
        map.put("label", 0);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).createGroup(map), new ResultListener<YMGroupEntity>() {
            @Override
            public void onSuccess(YMGroupEntity data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 创建聊天室
     *
     * @param roomAvatar
     * @param roomName
     * @param uidList
     * @param callback
     */
    public static void createRoom(String roomAvatar, String roomName, String uidList, final YMResultCallback<YMRoomEntity> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("groupAvatar", roomAvatar);
        map.put("groupName", roomName);
        map.put("uidList", uidList);
        map.put("groupType", 2);
        map.put("label", 0);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).createRoom(map), new ResultListener<YMRoomEntity>() {
            @Override
            public void onSuccess(YMRoomEntity data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }


    /**
     * 加入聊天室
     *
     * @param groupId
     * @param callback
     */
    public static void joinRoom(String groupId, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).joinRoom(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 解散聊天室
     *
     * @param groupId
     * @param callback
     */
    public static void dismissRoom(String groupId, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).dismissRoom(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 禁言用户
     *
     * @param groupId
     * @param userId
     * @param callback
     */
    public static void banRoomUser(String groupId, String userId, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("uid", userId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).banRoomUser(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 解除禁言用户
     *
     * @param groupId
     * @param userId
     * @param callback
     */
    public static void openRoomUser(String groupId, String userId, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("uid", userId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).openRoomUser(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 聊天室邀请用户
     *
     * @param groupId
     * @param uidList
     * @param callback
     */
    public static void inviteRoom(String groupId, List<String> uidList, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("uidList", uidList);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).inviteRoom(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 聊天室请离用户
     *
     * @param groupId
     * @param uidList
     * @param callback
     */
    public static void kickRoom(String groupId, List<String> uidList, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("uidList", uidList);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).kickRoom(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 离开聊天室
     *
     * @param groupId
     * @param callback
     */
    public static void leaveRoom(String groupId, final YMResultCallback<Object> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).leaveRoom(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 邀请好友加入群组
     *
     * @param groupId  群组id
     * @param uidList  好友id
     * @param callback
     */
    public static void groupInvite(String groupId, String uidList, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("groupId", groupId);
        map.put("uidList", uidList);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).groupInvite(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 踢人
     *
     * @param groupId  群组id
     * @param uidList  用户id数组
     * @param callback
     */
    public static void groupKick(String groupId, List<String> uidList, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        map.put("uidList", uidList);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).groupKick(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 解散群组
     *
     * @param groupId
     * @param callback
     */
    public static void dismissGroupWithGroupId(String groupId, final YMResultCallback<Boolean> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).dismissGroupWithGroupId(map), new ResultListener<Object>() {
            @Override
            public void onSuccess(Object data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(true);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 获取群详情
     *
     * @param groupId
     * @param callback
     */
    public static void getGroupDetail(String groupId, final YMResultCallback<YMGroupEntity> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gid", groupId);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).getGroupDetail(map), new ResultListener<YMGroupEntity>() {
            @Override
            public void onSuccess(YMGroupEntity data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 申请好友列表
     *
     * @param pageIndex
     * @param callback
     */
    public static void applyUserList(int pageIndex, int pageSize, final YMResultCallback<YMApplyUserListEntity> callback) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).applyUserList(map), new ResultListener<YMApplyUserListEntity>() {
            @Override
            public void onSuccess(YMApplyUserListEntity data) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onCallback(data);
                    }
                });
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }

    /**
     * 发送文件类的消息消息
     */

    public static void sendFileMessage(YMMessage message, final YMResultCallback<Boolean> callback) {
        YMMessageContent content = message.getContent();
        ArrayList<File> files = new ArrayList<>();
        //根据文件类型获取文件的路径
        if (content instanceof YMVoiceMessage) {
            files.add(new File(((YMVoiceMessage) content).getLocalPath()));
        } else if (content instanceof YMImageMessage) {
            files.add(new File((((YMImageMessage) content).getLocalPath())));
        } else if (content instanceof YMVideoMessage) {
            files.add(new File((((YMVideoMessage) content).getLocalPath())));
            files.add(new File((((YMVideoMessage) content).getLocalThumbnail())));
        } else if (content instanceof YMFileMessage) {
            files.add(new File((((YMVoiceMessage) content).getLocalPath())));
        }

        if (files == null || files.isEmpty()) {
            Log.e(TAG, "filePaths is null");
            return;
        }
        for (File file : files) {
            if (!file.exists()) {
                Log.e(TAG, file.getAbsolutePath() + " is  not exists");
                return;
            }
        }

        //先进行文件上传
        NetModel.getInstance().request(RetrofitHelper.getRequest(YMClientService.class).upLoadFiles(
                RetrofitHelper.covertFiles2Body("files", files)
        ), new ResultListener<String>() {
            @Override
            public void onSuccess(String obj) {
                Log.e(TAG, "文件上传成功返回路径：" + obj);
                //上传成功生成文件的 路径
                if (content instanceof YMVoiceMessage) {
                    ((YMVoiceMessage) content).setUrl(obj);
                } else if (content instanceof YMImageMessage) {
                    ((YMImageMessage) content).setUrl(obj);
                } else if (content instanceof YMVideoMessage) {
                    String[] array = obj.split(",");

                    ((YMVideoMessage) content).setUrl(array[0]);
                    ((YMVideoMessage) content).setThumbnail(array[1]);
                } else if (content instanceof YMFileMessage) {
                    ((YMFileMessage) content).setUrl(obj);
                }
                sendMessage(message, callback);
            }

            @Override
            public void onError(NetException netException) {
                SingletonHolder.sInstance.runUIThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFail(netException.getCode());
                    }
                });
            }
        });
    }


    /**
     * 设置webrtc 消息回调
     */
    public static void setRTCRecive(final MessageCallback callback) {
        SingletonHolder.sInstance.setRtcCallback(callback);
    }

}
